<template>
  <div class="aftersale-container">
    <el-container>
      <el-header>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-input
              v-model="searchInput"
              placeholder="请输入售后编号/用户名"
              @keyup.enter="handleSearch"
            >
              <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
            </el-input>
          </el-col>
          <el-col :span="6">
            <el-select
              v-model="afterSalesStatus"
              placeholder="请选择售后状态"
              @change="handleSearch"
              style="width: 100%"
            >
              <el-option
                v-for="item in afterSalesStatusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="width: 100%"
              @change="handleSearch"
            ></el-date-picker>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" @click="handleSearch">筛选</el-button>
            <el-button @click="exportData">导出</el-button>
          </el-col>
        </el-row>
      </el-header>









      <el-main>
        <el-table :data="tableData" border style="width: 100%">
          <el-table-column prop="id" label="售后编号" width="100"></el-table-column>
          <!-- <el-table-column prop="orderId" label="订单号" width="100" ></el-table-column> -->
          <el-table-column prop="username" label="用户姓名" width="200"></el-table-column>
          <el-table-column prop="status" label="处理状态" width="100">
              <template slot-scope="scope">
              <span v-if="scope.row.status === '0'">待处理</span>
          
              <span v-if="scope.row.status === '3'">退款中</span>
              <span v-if="scope.row.status === '4'">退款退货中</span>
              <span v-if="scope.row.status === '5'">退货换货中</span>
              <span v-if="scope.row.status === '6'">售后关闭</span>
              </template>
          </el-table-column>
          <el-table-column prop="reviewstatus" label="审核状态" width="100">
              <template slot-scope="scope">
              <span v-if="scope.row.reviewstatus === '0'">待审核</span>
              <span v-if="scope.row.reviewstatus === '1'">审核通过</span>
              <span v-if="scope.row.reviewstatus === '2'">审核未通过</span>
      
              </template>
          </el-table-column>
          <el-table-column prop="result" label="审核结果" width="100"></el-table-column>
          <el-table-column prop="reason" label="原因" width="100"></el-table-column>
          <el-table-column prop="orderRealFee" label="订单金额" width="100"></el-table-column>
          <el-table-column prop="refundAmount" label="退款金额" width="100"></el-table-column>
          <el-table-column prop="comments" label="售后备注" width="150"></el-table-column>
          <el-table-column prop="overdueTime" label="超时时间" width="100"></el-table-column>
          <el-table-column label="操作" width="100">
            <template slot-scope="scope">
              <el-button @click="handleOperation(scope.$index, scope.row)">处理</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-main>










      <el-row>
            <el-col :span="24">
                <!-- 放分页
         layout，表示需要显示的内容
         page-size设置每页多少条-->
                <el-pagination
                        background
                        :page-sizes="[3, 5, 10, 30]"
                        :page-size="pageSize"
                        :current-page="pageNum"
                        layout="total,sizes,prev, pager, next"
                        :total="total"
                        @next-click="nextPage"
                        @prev-click="prevPage"
                        @current-change="changePage"
                        @size-change="changeSize"
                >
                </el-pagination>
            </el-col>
        </el-row>







    </el-container>

    <!-- 审核弹窗 -->
    <el-dialog title="售后审核" :visible.sync="auditDialogVisible" width="30%">
      <el-form :model="auditForm" label-width="100px">
        <el-form-item label="审核结果">
          <el-radio-group v-model="auditForm.result">
            <el-radio label="1">通过</el-radio>
            <el-radio label="2">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核备注">
          <el-input type="textarea" v-model="auditForm.comments"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="auditDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAudit">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 退款处理弹窗 -->
    <el-dialog title="退款处理" :visible.sync="refundDialogVisible" width="40%">
      <el-form :model="refundForm" label-width="100px">
        <el-form-item label="订单金额">
          <span>{{ currentRow.orderRealFee }}</span>
        </el-form-item>
        <el-form-item label="申请退款金额">
          <span>{{ currentRow.refundAmount }}</span>
        </el-form-item>
        <el-form-item label="实际退款金额">
          <el-input-number 
            v-model="refundForm.actualRefund" 
            :min="0" 
            :max="currentRow.refundAmount || currentRow.orderRealFee" 
            :precision="2">
          </el-input-number>
        </el-form-item>
        <el-form-item label="退款方式">
          <el-select v-model="refundForm.refundMethod">
            <el-option label="原路退回" value="1"></el-option>
            <el-option label="退到余额" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="处理备注">
          <el-input type="textarea" v-model="refundForm.comments"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="refundDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitRefund">确认退款</el-button>
      </span>
    </el-dialog>

    <!-- 退款退货处理弹窗 -->
    <el-dialog title="退款退货处理" :visible.sync="refundReturnDialogVisible" width="40%">
      <el-form :model="refundReturnForm" label-width="120px">
        <el-form-item label="退货物流信息">
          <el-form-item label="物流公司">
            <el-select v-model="refundReturnForm.logisticsCompany">
              <el-option label="顺丰速运" value="SF"></el-option>
              <el-option label="中通快递" value="ZTO"></el-option>
              <el-option label="圆通速递" value="YTO"></el-option>
              <!-- 更多物流公司选项 -->
            </el-select>
          </el-form-item>
          <el-form-item label="物流单号">
            <el-input v-model="refundReturnForm.trackingNumber"></el-input>
          </el-form-item>
        </el-form-item>
        <el-form-item label="退货商品检查">
          <el-checkbox-group v-model="refundReturnForm.checkItems">
            <el-checkbox label="包装完好">包装完好</el-checkbox>
            <el-checkbox label="商品完整">商品完整</el-checkbox>
            <el-checkbox label="配件齐全">配件齐全</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="实际退款金额">
          <el-input-number 
            v-model="refundReturnForm.actualRefund" 
            :min="0" 

             :max="currentRow.refundAmount || currentRow.orderRealFee" 
            

            :precision="2">
          </el-input-number>
        </el-form-item>
        <el-form-item label="处理备注">
          <el-input type="textarea" v-model="refundReturnForm.comments"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="refundReturnDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitRefundReturn">确认处理</el-button>
      </span>
    </el-dialog>

    <!-- 商品搜索选择弹框 -->
    <el-dialog title="选择换货商品" :visible.sync="productSelectDialogVisible" width="50%">
      <div class="search-box">
        <el-input
          v-model="productSearchInput"
          placeholder="请输入商品名称"
          @keyup.enter="searchProducts"
          style="width: 300px;"
        >
          <el-button slot="append" icon="el-icon-search" @click="searchProducts"></el-button>
        </el-input>
      </div>

      <el-table
        :data="searchProductList"
        border
        style="width: 100%"
        @selection-change="handleProductSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="itemName" label="商品名称"></el-table-column>
        <el-table-column prop="itemType" label="类型"></el-table-column>
        <el-table-column prop="salePrice" label="价格"></el-table-column>
        <el-table-column prop="stock" label="库存"></el-table-column>
        <el-table-column label="数量" width="150">
          <template slot-scope="scope">
            <el-input-number 
              v-model="scope.row.exchangeQuantity" 
              :min="1" 
              :max="scope.row.stock"
              size="small">
            </el-input-number>
          </template>
        </el-table-column>
      </el-table>

      <span slot="footer">
        <el-button @click="productSelectDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmProductSelection">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改换货处理弹窗 -->
    <el-dialog title="换货处理" :visible.sync="exchangeDialogVisible" width="40%">
      <el-form :model="exchangeForm" label-width="120px">
        <el-form-item label="换货商品信息">
          <div class="selected-products">
            <el-button type="primary" @click="openProductSelect" size="small">
              选择换货商品
            </el-button>
            <el-table :data="exchangeForm.selectedProducts" border>
              <el-table-column prop="itemName" label="商品名称"></el-table-column>
              <el-table-column prop="itemType" label="类型"></el-table-column>
              <el-table-column prop="exchangeQuantity" label="数量"></el-table-column>
              <el-table-column label="操作" width="100">
                <template slot-scope="scope">
                  <el-button 
                    type="text" 
                    @click="removeSelectedProduct(scope.$index)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>
        <el-form-item label="换货物流信息">
          <el-form-item label="收货地址">
            <el-input v-model="exchangeForm.returnAddress" type="textarea"></el-input>
          </el-form-item>
          <el-form-item label="物流公司">
            <el-select v-model="exchangeForm.logisticsCompany">
              <el-option label="顺丰速运" value="SF"></el-option>
              <el-option label="中通快递" value="ZTO"></el-option>
              <el-option label="圆通速递" value="YTO"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="物流单号">
            <el-input v-model="exchangeForm.trackingNumber"></el-input>
          </el-form-item>
        </el-form-item>
        <el-form-item label="处理备注">
          <el-input type="textarea" v-model="exchangeForm.comments"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="exchangeDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitExchange">确认发货</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      searchInput: '',
      selectedCustomer: '',
      afterSalesMethod: '',
      afterSalesStatus: '',
      deliveryStatus: '',
      dateRange: [],
      tableData: [
        // Your table data here
      ],
      customerOptions: [
        { value: 'option1', label: '选项1' },
        { value: 'option2', label: '选项2' }
      ],
      afterSalesOptions: [
        { value: 'option1', label: '选项1' },
        { value: 'option2', label: '选项2' }
      ],
      afterSalesStatusOptions: [
        { value: '', label: '全部' },
        { value: '0', label: '待处理' },
        { value: '3', label: '退款中' },
        { value: '4', label: '退款退货中' },
        { value: '5', label: '退货换货中' },
        { value: '6', label: '售后关闭' }
      ],
      deliveryStatusOptions: [
        { value: '0', label: '未发货' },
        { value: '1', label: '已发货' },
        { value: '2', label: '已收货' }
      ],

      // 各类弹窗显示控制
      auditDialogVisible: false,
      refundDialogVisible: false,
      refundReturnDialogVisible: false,
      exchangeDialogVisible: false,

      // 审核表单
      auditForm: {
        result: '',
        comments: ''
      },

      // 退款表单
      refundForm: {
        actualRefund: 0,
        refundMethod: '1',
        comments: ''
      },

      // 退款退货表单
      refundReturnForm: {
        logisticsCompany: '',
        trackingNumber: '',
        checkItems: [],
        actualRefund: 0,
        comments: ''
      },

      // 换货表单
      exchangeForm: {
        returnAddress: '',
        logisticsCompany: '',
        trackingNumber: '',
        comments: '',
        selectedProducts: []  // 已选择的换货商品列表
      },

      // 商品选择相关
      productSelectDialogVisible: false,
      productSearchInput: '',
      searchProductList: [],
      selectedProducts: [],

      // 添加 currentRow
      currentRow: {
        id: '',
        orderId: '',
        orderAmount: 0,
        refundAmount: 0,
        status: '',
        products: []  // 用于换货时显示商品信息
      },

      // 查询参数对象
      params: {
        startDate: '',
        endDate: '',
        status: '',
        keyword: ''
      },

      // 分页参数
      pageSize: 5,
      pageNum: 1,
      total: 0,
    };
  },
  methods: {
    queryAllafter() {
      // 处理日期格式
      if (this.dateRange && this.dateRange.length === 2) {
        this.params.startDate = this.formatDate(this.dateRange[0]);
        this.params.endDate = this.formatDate(this.dateRange[1]);
      } else {
        this.params.startDate = '';
        this.params.endDate = '';
      }

      // 更新其他查询参数
      this.params.status = this.afterSalesStatus || '';
      this.params.keyword = this.searchInput || '';

      // 构建分页参数
      let pageData = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        param: this.params
      };

      // 发起POST请求
      this.$axios.post('/apib/aftersales/queryAllAfter', pageData).then(resp => {
        if (resp.data.code === 200) {
          this.tableData = resp.data.data.list;
          this.total = resp.data.data.total;
          console.log('查询结果：', resp.data.data);
        } else {
          this.$message.error(resp.data.message || '查询失败');
        }
      }).catch(error => {
        this.$message.error('请求失败：' + error.message);
      });
    },
    handleSearch() {
      this.pageNum = 1; // 重置到第一页
      this.queryAllafter();
    },
    exportData() {
      // TODO: 实现导出功能
      this.$message.info('导出功能开发中');
    },
    handleOperation(index, row) {
      this.currentRow = row;
      
      switch(row.status) {
        case '0':
          this.auditDialogVisible = true;
          break;
        case '3':
          this.refundDialogVisible = true;
          break;
        case '4':
          this.refundReturnDialogVisible = true;
          break;
        case '5':
          this.exchangeDialogVisible = true;
          break;
      }
    },

    // 提交审核
    submitAudit() {
      if (this.auditForm.result === '1') {
        // 审核通过
        this.$axios.get('/apib/aftersales/passAfterReviewstatus/' + this.currentRow.id).then(resp => {
          if(resp.data.code === 200) {
            this.$message.success('审核通过成功');
            this.auditDialogVisible = false;
            this.queryAllafter();  // 刷新列表
          } 
        });
      } 
      if(this.auditForm.result === '2'){
        this.$axios.get('/apib/aftersales/refuseAfterReviewstatus/' + this.currentRow.id).then(resp => {
          if(resp.data.code === 200) {
            this.$message.success('审核拒绝成功');
            this.auditDialogVisible = false;
            this.queryAllafter();  // 刷新列表
          } 
        
        });
      }
    },

    // 提交退款
    submitRefund() {
      const params = {
        id: this.currentRow.id,
        actualRefund: this.refundForm.actualRefund,
        refundMethod: this.refundForm.refundMethod,
        comments: this.refundForm.comments
      };

      this.$axios.get('/apib/aftersales/refundDiscount/' + this.currentRow.id + '/' + this.refundForm.actualRefund).then(resp => {
        if(resp.data.code === 200) {
          this.$message.success('退款处理成功');
          this.refundDialogVisible = false;
          this.queryAllafter();
        }
      });
    },

    // 提交退款退货
    submitRefundReturn() {
      this.$axios.get('/apib/aftersales/dealBackAfterProductAndMoney/' + this.currentRow.id + '/' + this.refundReturnForm.actualRefund).then(resp => {
        if(resp.data.code === 200) {
          this.$message.success('退款退货处理成功');
          this.refundReturnDialogVisible = false;
          this.queryAllafter();  // 刷新列表
        } else {
          this.$message.error(resp.data.message || '处理失败');
        }
      }).catch(error => {
        this.$message.error('请求失败：' + error.message);
      });
    },

    // 搜索商品
    searchProducts() {
      this.$axios.get('/apip/getProductByName/'+ this.productSearchInput).then(resp => {
        if(resp.data.code === 200) {
          // 打印返回数据，检查数据结构
          console.log('搜索结果：', resp.data.data);
          
          // 确保每个商品对象都有exchangeQuantity属性
          this.searchProductList = resp.data.data.map(item => ({
            ...item,
            exchangeQuantity: 1  // 默认数量为1
          }));
          
          // 再次打印处理后的数据
          console.log('处理后的搜索列表：', this.searchProductList);
        } else {
          this.$message.error(resp.data.message || '搜索失败');
        }
      }).catch(error => {
        this.$message.error('搜索请求失败：' + error.message);
      });
    },

    // 打开商品选择弹框
    openProductSelect() {
      this.productSelectDialogVisible = true;
      // 清空之前的搜索结果
      this.searchProductList = [];
      this.productSearchInput = '';
    },

    // 处理商品选择变化
    handleProductSelectionChange(selection) {
      this.selectedProducts = selection;
      console.log('选中的商品：', selection);
    },

    // 确认商品选择
    confirmProductSelection() {
      // 修改商品信息的映射
      const newProducts = this.selectedProducts.map(product => ({
        ...product,  // 保留原有的所有属性
        itemName: product.itemName,
        itemType: product.itemType,
        exchangeQuantity: product.exchangeQuantity || 1,
        salePrice: product.salePrice,
        stock: product.stock
      }));

      // 将选择的商品添加到换货表单中
      this.exchangeForm.selectedProducts = [
        ...this.exchangeForm.selectedProducts,
        ...newProducts
      ];

      this.productSelectDialogVisible = false;
      this.selectedProducts = [];
      this.productSearchInput = '';
      this.searchProductList = [];
    },

    // 移除已选择的商品
    removeSelectedProduct(index) {
      this.exchangeForm.selectedProducts.splice(index, 1);
    },

    // 更新提交换货方法
    submitExchange() {
      const params = {
        id: this.currentRow.id,
        returnAddress: this.exchangeForm.returnAddress,
        logisticsCompany: this.exchangeForm.logisticsCompany,
        trackingNumber: this.exchangeForm.trackingNumber,
        comments: this.exchangeForm.comments,
        products: this.exchangeForm.selectedProducts  // 添加商品信息
      };

      this.$axios.post('/apib/aftersales/exchangeAfterProduct', params).then(resp => {
        if(resp.data.code === 200) {
          this.$message.success('换货处理成功');
          this.exchangeDialogVisible = false;
          this.queryAllafter();
          
          // 清空表单
          this.exchangeForm.selectedProducts = [];
        }
      });
    },

    // 格式化日期
    formatDate(date) {
      if (!date) return '';
      const d = new Date(date);
      const year = d.getFullYear();
      const month = String(d.getMonth() + 1).padStart(2, '0');
      const day = String(d.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },

    handleCurrentChange(val) {
        this.currentPage = val;
        // 分页逻辑
      },
      nextPage(val) {
                    //     下一页  回调参数：val 当前页
                    this.pageNum = val
                    this.queryAllafter();
                },
                prevPage(val) {
                    //     下一页  回调参数：val 当前页
                    this.pageNum = val
                    this.queryAllafter();
                },
                changePage(val) {
                    this.pageNum = val
                    this.queryAllafter();
                },
                changeSize(val) {
                    this.pageNum = 1
                    this.pageSize = val
                    this.queryAllafter()
                },
                queryInfo() {
                    this.pageNum = 1
                    this.queryAllafter()
                },restart(){
                    this.params={}
                    this.queryAllafter();
                }
    
  },
  created() {
      this.queryAllafter()
  }
};
</script>

<style scoped>
.el-main {
margin-top: 120px; /* 增加顶部间距 */
}

.search-box {
margin-bottom: 20px;
}

.selected-products {
margin-bottom: 20px;
}

.selected-products .el-button {
margin-bottom: 10px;
}

.aftersale-container {
/* background-image: url('../../assets/head.jpg'); */
background-size: cover;  /* 或者 contain，根据需要调整 */
background-position: center;
background-repeat: no-repeat;
min-height: 100vh;  /* 确保背景图片填充整个视口高度 */
}
</style>